package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.mapper.NoticeMapper;
import cn.tedu._03vehicle.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Tag(name = "03-资讯管理模块")
@RequestMapping("/v1/notice/")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 1.首页列表
     */
    @GetMapping("list")
    @Operation(summary = "资讯列表")
    @ApiOperationSupport(order = 10)
    public JsonResult listNotice(){
        /*
            缓存设计:
            * 数据类型:字符串
            * redis-key: vehicle_index
            * redis-value: List<NoticeListVO> ---> '[{},{},{},{},{},{},{},{},{},{}]'
            *************************************************
            1.查询缓存中是否存在首页列表数据;
            2.缓存中存在,则直接返回;
            3.缓存中不存在:
              3.1 到MySQL中查询数据;
              3.2 将查询结果保存到缓存中;
              3.3 返回查询结果;
         */
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable redis_data = ops.get("vehicle_index");
        if (redis_data != null){//缓存中存在数据
            log.debug("数据来自Redis数据库...");
            return JsonResult.ok(redis_data);
        }
        //缓存中不存在数据
        List<NoticeListVO> noticeListVOS = noticeMapper.selectNoticeList();
        //保存数据到缓存中
        ops.set("vehicle_index", (Serializable) noticeListVOS, 30, TimeUnit.SECONDS);
        log.debug("数据来自MySQL数据库...");

        //{"state":2000, "message":"操作成功", "data": [{},{},{},{},{},{},{},{},{},{}]}
        return JsonResult.ok(noticeListVOS);
    }
}








